# -*- coding:utf-8 -*-
# 黑cyc宇
from flask import Blueprint, request, jsonify
from flask import current_app as bot
from bot.plugins.fixed._on_env import *
from bot.kernel.session import *
import re, json, urllib


route_parse_handler = Blueprint('route_parse_handler', __name__)

@route_parse_handler.route('/parse')
def parse():
    info = request.args
    event = info['event']

    if event in ['friend_msg', 'group_msg']:
        solve_command(info)
    elif event in ['group_member_add', 'group_member_decrease', 'friend_verify']:
        solve_request(event, info)
    elif event in ['received_transfer', 'scan_cash_money', 'contacts_change', 'sys_msg']:
        solve(info, 'notice')
    elif event in ['init', 'enable', 'login', 'stop']:
        eval(f'{event}')(bot.session)
    elif event == 'get_msg':
        try:
            ret = bot.ret_msg_dict[int(info['uuid'])]
            return jsonify({'data': ret, 'code': 200})
        except: pass
    return ''

def util_solve_command(cmd, args=[]):
    for cmds, func in bot.cmd_route['command']:
        if cmd in cmds: 
            func(args, bot.session)

def solve_command(info):
    bot.session = CommandSession(info)
    # 1/文本消息 3/图片消息 34/语音消息  42/名片消息  43/视频 47/动态表情 48/地理位置  49/分享链接  2001/红包  2002/小程序  2003/群邀请
    msg_type = int(info['type'])
    if msg_type == 1: # 文本消息
        cmd, args = get_cmd_arg(info['msg'])
        util_solve_command(cmd, args)
    elif msg_type == 3: # 图片消息
        # msg = 'image_path' # 图片地址
        util_solve_command('media_image', info['msg'])
    elif msg_type == 34: # 语音消息
        # msg = 'audio_path' # 语音地址
        util_solve_command('media_audio', info['msg'])
    elif msg_type == 43: # 视频
        # msg = 'video_path' # 视频地址
        util_solve_command('media_video', info['msg'])
    elif msg_type == 48: # 地理位置
        # msg = {"x":"33.070225","y":"115.595291","desc":"刘盆窑村(阜阳市颍泉区)","title":"颍泉区023县道"}
        util_solve_command('media_location', eval(info['msg']))
    # elif msg_type == 42: # 名片消息
    #     msg = '''<msg
    #         bigheadimgurl="http://wx.qlogo.cn/mmhead/ver_1/Ux5ibGcC6RFIdoW7YibmWO3C9VduZQoVHqXw1w1ymibkrn9MITxKeGFdSaYyhn2Agic5L5OiarFCcyPuK5qibBDmoBFEaic6ibRiaULO2KEtJ9BLbCgM/0"
    #         smallheadimgurl="http://wx.qlogo.cn/mmhead/ver_1/Ux5ibGcC6RFIdoW7YibmWO3C9VduZQoVHqXw1w1ymibkrn9MITxKeGFdSaYyhn2Agic5L5OiarFCcyPuK5qibBDmoBFEaic6ibRiaULO2KEtJ9BLbCgM/132"
    #         username="v1_a6658eb1270e6e7b750b7e37c9db64072878b0e82b43c2b98327867c5815925ea9ebc21526846ee42a75f33ba5c307ad@stranger"
    #         nickname="下一个路口"
    #         fullpy="下一个路口"
    #         shortpy="XYGLK"
    #         alias=""
    #         imagestatus="3"
    #         scene="17"
    #         province="中国大陆"
    #         city="上海"
    #         sign=""
    #         sex="1"
    #         certflag="0"
    #         certinfo=""
    #         brandIconUrl=""
    #         brandHomeUrl=""
    #         brandSubscriptConfigUrl=""
    #         brandFlags="0"
    #         regionCode="CN_Shanghai"
    #         antispamticket="v2_75bb0f0a15c60764857b348b89d81183389aa2719aa497d743fb9e1510bf3454c8c66d71377e1f7b45d3398f4ac92da4e17c4bca7ac64f7e52c6a4f9a0b95e1331a1dbd75d8be202c1dc2591ad4242fa97aaa8c0d860679e92beabb991fff9231e274d4698821c5e2457dc86bf468f29ab40b6566c5a05e333ee23b3e2f9e68bb225c24556664ea2a04fe38fd0a52760478d4a60867d4dda4dea44e7ef4ed467d26371d64a29a8cb7359fc2a3d71247564addfdd265cc082e53398151291b0c18ac3564224376d7faefd438f2acc7937@stranger"
    #         />
    #     '''
    # elif msg_type == 47: # 动态表情
    # elif msg_type == 49: # 分享链接
    #     msg = '''
    #     <?xml version="1.0"?>
    #     <msg>
    #     <appmsg appid="wx85686879e8891882" sdkver="0">
    #     <title>flask获取绝对位置 - 百度</title>
    #     <des>flask获取绝对位置 - 百度</des>
    #     <username />
    #     <action>view</action>
    #     <type>5</type>
    #     <showtype>0</showtype>
    #     <content />
    #     <url>https://m.baidu.com/s?from=2001p
    #     '''
    # elif msg_type == 2001: #红包
    #     msg = '收到红包，请在手机上查看'
    # elif msg_type == 2002: #小程序
    #     msg = '''
    #     <?xml version="1.0"?>
    #     <msg>
    #     <appmsg appid="" sdkver="0">
    #     <title>五分钟学算法</title>
    #     <des />
    #     <username />
    #     <action>view</action>
    #     <type>33</type>
    #     <showtype>0</showtype>
    #     <content />
    #     <url>https://mp.weixin.qq.com/mp/waerrpage?appid=wx4e0c3f9abc2fcd93
    #     '''
    # elif msg_type == 2003: #群邀请
    # else:
    #     print('-'*100)
    #     print('msg_type', msg_type, info['msg'])
    #     print('*'*100)

def solve_request(event, info):
    json_data = json.loads(urllib.parse.unquote(info['json_msg']))
    bot.session = RequestSession(info, info['json_msg'])
    for cmds, func in bot.cmd_route['request']:
        if event in cmds: func(json_data, bot.session)

def solve_notice(event, info):
    json_data = json.loads(urllib.parse.unquote(info['json_msg']))
    bot.session = NoticeSession(info, info['json_msg'])
    for cmds, func in bot.cmd_route['request']:
        if event in cmds: func(json_data, bot.session)

def get_cmd_arg(msg):
    temp = re.split('\s+', msg.strip()) # cmd 和 args 之间强制是 空格, 忽略多空格
    cmd, args = temp[0], temp[1:]

    arg_type = bot.config.get('ARG_TYPE', 'url')
    if arg_type == 'url':
        args = dict([arg.split('=') for arg in ' '.join(temp[1:]).split('&')]) if temp[1:] else {}
    elif arg_type == 'list': # 忽略多空格
        if bot.config['SEP'] != ' ': # 不用空格分隔参数
            args = re.split(f"{bot.config['SEP']}+", ' '.join(temp[1:])) if temp[1:] else []
        # else: # 本来就是空格分隔的

    return cmd, args
    # ret = msg.split(bot.config['SEP'])
